import axios from 'axios'
import io from 'socket.io-client'

export const MSG_LIST = 'MSG_LIST'
export const MSG_RECEIVE = 'MSG_RECEIVE'
export const MSG_READ = 'MSG_READ'
export const ON_SOCKET='ON_SOCKET'

const socket=io("http://localhost:9093")



function msgList(msgs,users,userid){
    return{
        type:MSG_LIST,
        payload:{
            msgs:msgs,
            users:users,
            userid:userid
        }
    }
}

function msgreceive(data,userid){
    return{
        type:MSG_RECEIVE,
        payload:{
            data:data,
            userid:userid
        }
    }
}

function msgread(from,num){
    return{
        type:MSG_READ,
        payload:{
            from:from,
            num:num
        }
    }
}


//获取列表
export function getMsgList() {
    return dispatch => {
        axios.get('/user/getmsglist')
            .then(res => {
                if (res.status === 200 && res.data.code === 0) {
                    dispatch(msgList(res.data.msgs,res.data.users,res.data.userid))
                }
            })
    }
}

//发送消息的请求
export function sendMessage({from,to,content}){
    return dispatch=>{
        socket.emit("sendMessage",{from,to,content})
    }
}

//接收消息
export function receiveMessage(){
    return (dispatch,getState)=>{
        socket.on("receiveMessage",function(data){
            const userid=getState().user._id
            dispatch(msgreceive(data,userid))
        })
    }
}

export function readMessage({from}){
    return (dispatch,getState)=>{
        axios.post('/user/updateChat',{from})
            .then(res=>{
                if(res.status===200&& res.data.code===0){
                    dispatch(msgread(res.data.from,res.data.num))
                }
            })
    }
}


export function onSocket(){
    return {
        type:ON_SOCKET,
        payload:true
    }
}



